package com.rainbow.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainbow.common.UserUtils;
import com.rainbow.entity.MsgContent;
import com.rainbow.entity.SysMsg;
import com.rainbow.entity.User;
import com.rainbow.mapper.SysMsgMapper;
import com.rainbow.service.SysMsgService;
import com.rainbow.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author rainbow
 **/
@Service
@Transactional
public class SysMsgServiceImpl extends ServiceImpl<SysMsgMapper, SysMsg> implements SysMsgService {

    @Autowired
    private UserService userService;

    @PreAuthorize("hasRole('ROLE_admin')")//只有管理员可以发送系统消息
    @Override
    public boolean sendMsg(MsgContent msg) {
        int result = baseMapper.sendMsg(msg);
        List<User> allHr = userService.getAllHr();
        int result2 = baseMapper.addMsg2AllHr(allHr, msg.getId());
        return result2 == allHr.size();
    }

    @Override
    public List<SysMsg> getSysMsgByPage(Integer page, Integer size) {
        int start = (page - 1) * size;
        return baseMapper.getSysMsg(start, size, UserUtils.getCurrentHr().getId());
    }

    @Override
    public boolean markRead(Long flag) {
        if (flag != -1) {
            return baseMapper.markRead(flag, UserUtils.getCurrentHr().getId()) == 1;
        }
        baseMapper.markRead(flag, UserUtils.getCurrentHr().getId());
        return true;
    }
}
